package com.springboot_redis.config;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.springboot_redis.domain.RedisKeys;
import com.springboot_redis.domain.RequestLimitConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WebHandler extends HandlerInterceptorAdapter {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private RequestLimitConfig requestLimitConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        log.info("拦截开始");

        String uri = request.getRequestURI().toString();
        String addr=request.getRemoteAddr();

        String limitKey = RedisKeys.REQUEST_LIMIT + ":" +addr+"-"+uri;
        System.out.println(limitKey);
        if(!redisTemplate.hasKey(limitKey)){
            redisTemplate.opsForValue().set(limitKey, 0);
        }
        long count = redisTemplate.opsForValue().increment(limitKey);
        if (count == 1) {
            redisTemplate.expire(limitKey, requestLimitConfig.getTime(), TimeUnit.SECONDS);
            log.info("设置过期时间：time={}, timeUnit={}", requestLimitConfig.getTime(), TimeUnit.SECONDS);
        }
        if (count > requestLimitConfig.getLimit()) {
            response.setContentType(MediaType.TEXT_PLAIN_VALUE);
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            response.getWriter().write("服务器繁忙,稍后再试");
            return false;
        }

        return true;
    }

}
